package cn.xjt.gaoji;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 买票系统会出现不安全
 * 需要加上锁
 * 通过ReenTrantlock对象进行加锁，解锁
 * private final ReentrantLock locks = new ReentrantLock();
 * @author xujiangtao
 * @create 2020-08-01-16:59
 */
public class TestReentrantLock {
    public static void main(String[] args) {
        buyticket person = new buyticket();
        Thread t = new Thread(person);
        t.start();
        t=new Thread(person);
        t.start();
        t= new Thread(person);
        t.start();
    }

}
//一个卖票的类
class buyticket implements Runnable{
    //Reentrantlock:可重进锁
    private final ReentrantLock locks = new ReentrantLock();
    //票数
    int ticket =10;
    @Override
    //重写的方法
    public void run() {
        while (true)
        {
            try {
                //开启一个锁        开启一个锁最好放在try语句
                locks.lock();
                if(ticket>0)
                {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticket--);
                }
                else
                {
                    System.out.println("你买的票已经被购完");
                    break;
                }
            }finally {
                //关闭一个锁
                locks.unlock();
            }
        }
    }
}
